package com.easymall.util;

import java.sql.*;

public class TransactionManager {

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private TransactionManager(){}

    /**
     * 开始事务
     * @throws SQLException 数据库失败
     */
    public static void startTransaction() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        threadLocal.set(connection);
    }

    /**
     * 获取当前线程保存的数据库连接
     * @return Connection数据库连接对象
     */
    public static Connection getConnection(){
        return threadLocal.get();
    }

    /**
     * 事务提交
     * @throws SQLException 数据库失败
     */
    public static void commitTransaction() throws SQLException {
        threadLocal.get().commit();
    }

    /**
     * 事务回滚操作
     * @throws SQLException 数据库失败
     */
    public static void rollbackTransaction() throws SQLException {
        threadLocal.get().rollback();
    }

    /**
     * 事务回滚到保存点
     * @param savepoint 事务保存点
     * @throws SQLException 数据库失败
     */
    public static void rollbackTransaction(Savepoint savepoint) throws SQLException {
        threadLocal.get().rollback(savepoint);
    }

    /**
     * 归还连接，并释放资源
     * @param resultSet 要释放的结果集对象
     * @param statement 要释放的SQL执行器对象
     */
    public static void close(ResultSet resultSet, Statement statement){
        JDBCUtils.close(resultSet, statement, threadLocal.get());
        threadLocal.remove();
    }


}
